from flask import Blueprint
from flask_login import login_required

from apps.a_common.db import safe_commit
from apps.a_common.log import MyLogger
from apps.a_common.permission import has_permission_decorate
from apps.a_common.request import assert_params_by_form
from apps.a_common.response import paginate_response, success_response
from apps.foundation import db
from apps.projects.forms import CheckListEditorForm, CheckListSearchForm
from apps.projects.models import CheckList, Process
from apps.projects.serializers import serialize_checklist, serialize_checklist_group_by_type
from apps.users.models import User

checklist_blueprint = Blueprint('checklist', __name__)
log = MyLogger('checklist views')


@checklist_blueprint.route('/checklist/<int:checklist_id>/', methods=['GET'])
@login_required
@has_permission_decorate('admin-checklist-view')
def _get_checklist(checklist_id):
    """
    查看一个清单条目的详情
    ---
    tags:
      - checklist
    parameters:
      - name: checklist_id
        in : path
        type: integer
        required: true
        description: 清单条目的id
    """
    checklist, user = db.session.query(CheckList, User).join(User, CheckList.user_id == User.id, isouter=True). \
        filter(CheckList.id == checklist_id).first_or_404()
    return success_response(serialize_checklist(checklist, user))


@checklist_blueprint.route('/checklist/', methods=['GET'])
@login_required
@has_permission_decorate('admin-checklist-view')
def _get_checklists():
    """
    获取清单列表
    ---
    tags:
      - checklist
    parameters:
      - name: process_id
        in : query
        type: integer
        required: false
        description: process id找清单
      - name: project_id
        in : query
        type: integer
        required: false
        description: project id找清单
      - name: type
        in : query
        type: integer
        required: false
        description: 查找类型
      - name: status
        in : query
        type: integer
        required: false
        description: 查找状态
      - name: page_id
        in : query
        type: integer
        required: false
        default: 1
        description: 页码
      - name: page_size
        in : query
        type: integer
        required: false
        default: 20
        description: 每页的大小
    """
    form = assert_params_by_form(CheckListSearchForm)
    queryset = CheckList.query
    if form.get('process_id'):
        queryset = queryset.filter(CheckList.process_id == form['process_id'])
    if form.get('project_id'):
        queryset = queryset.join(Process, Process.id == CheckList.process_id).filter(Process.project_id == form['project_id'])
    if form.get('status'):
        queryset = queryset.filter(CheckList.status == form['status'])
    if form.get('type'):
        queryset = queryset.filter(CheckList.type == form['type'])

    return success_response(serialize_checklist_group_by_type(queryset.all()))
    # return paginate_response(queryset, serialize_checklist)


@checklist_blueprint.route('/checklist/', methods=['POST'])
@login_required
@has_permission_decorate('admin-checklist-create')
def _post_checklist():
    """
    新建清单条目
    ---
    tags:
      - checklist
    parameters:
      - name: name
        in : formData
        type: string
        required: true
        description: 清单条目的名字
      - name: start_at
        in : formData
        type: integer
        required: false
        description: 项目的开始时间
      - name: end_at
        in : formData
        type: integer
        required: false
        description: 项目的结束时间
      - name: status
        in : formData
        type: integer
        required: false
        description: 项目的结束时间
      - name: type
        in : formData
        type: integer
        required: false
        description: 清单条款的类型，1是代办，2是风险
      - name: process_id
        in : formData
        type: integer
        required: false
        description: 环节的id
      - name: user_id
        in : formData
        type: integer
        required: false
        description: user id
    """
    form = assert_params_by_form(CheckListEditorForm)
    checklist = CheckList()
    for key, value in form.items():
        setattr(checklist, key, value)
    db.session.add(checklist)
    safe_commit()
    return success_response(serialize_checklist(checklist))


@checklist_blueprint.route('/checklist/<int:checklist_id>/', methods=['PUT'])
@login_required
@has_permission_decorate('admin-checklist-change')
def _put_checklist(checklist_id):
    """
    修改清单条目
    ---
    tags:
      - checklist
    parameters:
      - name: checklist_id
        in : path
        type: integer
        required: true
        description: 清单条目的id
      - name: name
        in : formData
        type: string
        required: true
        description: 清单条目的名字
      - name: start_at
        in : formData
        type: integer
        required: false
        description: 项目的开始时间
      - name: end_at
        in : formData
        type: integer
        required: false
        description: 项目的结束时间
      - name: status
        in : formData
        type: integer
        required: false
        description: 项目的结束时间
      - name: type
        in : formData
        type: integer
        required: false
        description: 清单条款的类型，1是代办，2是风险
      - name: process_id
        in : formData
        type: integer
        required: false
        description: 环节的id
      - name: user_id
        in : formData
        type: integer
        required: false
        description: user id
    """
    form = assert_params_by_form(CheckListEditorForm)
    checklist = CheckList.query.filter(CheckList.id == checklist_id).first_or_404()
    for key, value in form.items():
        setattr(checklist, key, value)
    safe_commit()
    return success_response(serialize_checklist(checklist))
